package com.zy.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zy.pojo.Permission;
import com.zy.pojo.Role;
import com.zy.pojo.User;
import com.zy.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SpringSecurityUserService implements UserDetailsService {

	@Reference
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//查询数据库(多表关联查询)
		User user=userService.findUserByname(username);
		//创建 权限 角色 集合
		List<GrantedAuthority> list = new ArrayList<>();
		for (Role role : user.getRoles()) {
			list.add(new SimpleGrantedAuthority(role.getKeyword()));
			for (Permission permission : role.getPermissions()) {
				list.add(new SimpleGrantedAuthority(permission.getKeyword()));
			}
		}
		//鉴权、认证、授权
		org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
		return securityUser;
	}
}
